<?php
class main extends spController
{
	private $appkeys;
	
	function __construct(){
		parent::__construct();
		$this -> appkeys = unserialize(spAccess('r','appkeys'));
	}
	
	function index(){
		
	}
	
	function gettrades(){
		import('./TopSdk.php');
		$sessions = spClass('m_top') -> getSessions();
		if(empty($sessions)) return FALSE;
		$c = new TopClient;
		for($i=0;isset($sessions[$i]);$i++){
			$c->appkey = $sessions[$i]['appkey'];
			$c->secretKey = $this -> appkeys[$sessions[$i]['appkey']];
			$req = new TradesSoldGetRequest;
			$req->setFields("tid,status,orders.title,orders.refund_status,orders.oid");
			$req->setStartCreated(date("Y-m-d H:i:s",time()-1800));
			$req->setEndCreated(date("Y-m-d H:i:s",time()+600));
			$req->setStatus("WAIT_SELLER_SEND_GOODS");
			$resp = $c->execute($req, $sessions[$i]['sessionkey']);
			if($resp -> code == '26' || $resp -> code == '27'){
				//session 过期
				spClass('m_top') -> sessionInvilid($sessions[$i]['nick']);
				continue;
			}
			foreach ($resp -> trades -> trade as $trade){
				if($trade -> status == 'WAIT_SELLER_SEND_GOODS'){
					foreach ($trade -> orders -> order as $order){
						$check = spClass('m_order') -> getOrder($order -> oid);
						if($check == FALSE){
							$alipay_no = $this->getalipay_no($trade -> tid, $sessions[$i]['sessionkey'],$c);
							spClass('m_order') -> updateOrder($order -> oid,$trade -> tid,$alipay_no,$order -> title,$sessions[$i]['id']);
						}
					}
				}
			}
		}
	}
	
	function getalipay_no($tid,$sessionkey,$c){
		$req = new TradeGetRequest;
		$req->setFields("alipay_no");
		$req->setTid($tid);
		$resp = $c->execute($req, $sessionkey);
		return $resp -> trade -> alipay_no;
	}
	
	function getrefunds(){
		import('./TopSdk.php');
		$sessions = spClass('m_top') -> getSessions();
		if(empty($sessions)) return FALSE;
		$c = new TopClient;
		for($i=0;isset($sessions[$i]);$i++){
			$c->appkey = $sessions[$i]['appkey'];
			$c->secretKey = $this -> appkeys[$sessions[$i]['appkey']];
			$req = new RefundsReceiveGetRequest;
			$req->setFields("oid,order_status");
			$req->setStartModified(date("Y-m-d H:i:s",time()-86400*31));
			$req->setEndModified(date("Y-m-d H:i:s",time()+600));
			$req->setPageSize(100);
			$resp = $c->execute($req, $sessions[$i]['sessionkey']);
			if($resp -> code == '26' || $resp -> code == '27'){
				//session 过期
				spClass('m_top') -> sessionInvilid($sessions[$i]['nick']);
				continue;
			}
			foreach ($resp -> refunds -> refund as $refund){
				spClass('m_order') -> setRefund($refund -> oid); 
			}
		}

	}
}